from jthread.frame import JFrame


class JStack:

    def __init__(self):
        self.size = 0
        self._top: JFrame = None
        self.maxSize = 0

    @staticmethod
    def newJStack(maxStack):
        stack = JStack()
        stack.size = 0
        stack.maxSize = maxStack
        stack._top = None
        return stack

    def push(self, frame: JFrame):
        if self.size >= self.maxSize:
            raise Exception("Stack overflow")
        if self._top is not None:
            frame.setPreFrame(self._top)
        self._top = frame
        self.size += 1

    def pop(self):
        if self._top is None:
            raise Exception("Stack underflow")
        frame = self._top
        self._top = frame.getPreFrame()
        self.size -= 1
        frame.setPreFrame(None)
        return frame

    def top(self):
        return self._top

    def isEmpty(self):
        return self._top is None

    def clear(self):
        while not self.isEmpty():
            self.pop()

    def getFrames(self):
        frames = []
        frame = self._top
        while frame is not None:
            frames.append(frame)
            frame = frame.getPreFrame()
        return frames
